/**
 * 物品全局管理模块（Vuex）
 * - 提供物品数据的读取与更新接口
 * - 通过 role/info 完成货币初始化，并在随后调用 /item/info 拉取背包道具
 * - 在任意接口返回包含 items 数组时（形如 [[id, count]]），可通过全局钩子自动更新本地状态
 * - 预定义与后端一致的物品ID常量
 */

import systemApi from '@/api/system'

// 物品ID常量，与后端 pkg/game_config/item.go 保持一致
export const ITEM_ID = {
  COIN: 1,           // 银两
  GOLD_COIN: 2,      // 元宝
  INVITE_SCORE: 3,   // 招募积分
  INVITE_LING: 4,    // 招募令
  PARTNER_EXCHANGE_LETTER: 26 // 五阶兑换令
}

const state = {
  // 货币类（特殊ID）
  currencies: {
    [ITEM_ID.COIN]: 0,
    [ITEM_ID.GOLD_COIN]: 0,
    [ITEM_ID.INVITE_SCORE]: 0,
    [ITEM_ID.INVITE_LING]: 0,
    [ITEM_ID.PARTNER_EXCHANGE_LETTER]: 0
  },
  // 背包道具（非货币）
  inventory: {}, // { [itemId]: count }
  // 加载状态
  loading: false,
  error: null,
  lastUpdatedAt: null
}

const mutations = {
  SET_LOADING(state, loading) {
    state.loading = loading
  },
  SET_ERROR(state, error) {
    state.error = error
  },
  CLEAR_ERROR(state) {
    state.error = null
  },
  SET_CURRENCIES(state, payload) {
    state.currencies = { ...state.currencies, ...payload }
  },
  SET_CURRENCY(state, { id, count }) {
    state.currencies = { ...state.currencies, [id]: count }
  },
  SET_INVENTORY_FROM_ARRAY(state, itemsArray) {
    const map = {}
    itemsArray.forEach(([id, count]) => {
      if (id === ITEM_ID.COIN || id === ITEM_ID.GOLD_COIN || id === ITEM_ID.INVITE_SCORE || id === ITEM_ID.INVITE_LING || id === ITEM_ID.PARTNER_EXCHANGE_LETTER) {
        // 货币不计入背包
        return
      }
      map[id] = count
    })
    state.inventory = map
    state.lastUpdatedAt = Date.now()
  },
  APPLY_ITEM_UPDATES(state, itemsArray) {
    // 根据 [[id, count]] 更新对应的货币或背包数量
    itemsArray.forEach(([id, count]) => {
      if (id === ITEM_ID.COIN || id === ITEM_ID.GOLD_COIN || id === ITEM_ID.INVITE_SCORE || id === ITEM_ID.INVITE_LING || id === ITEM_ID.PARTNER_EXCHANGE_LETTER) {
        state.currencies = { ...state.currencies, [id]: count }
      } else {
        const next = { ...state.inventory }
        next[id] = count
        state.inventory = next
      }
    })
    state.lastUpdatedAt = Date.now()
  },
  CLEAR_ITEMS(state) {
    state.inventory = {}
    state.currencies = {
      [ITEM_ID.COIN]: 0,
      [ITEM_ID.GOLD_COIN]: 0,
      [ITEM_ID.INVITE_SCORE]: 0,
      [ITEM_ID.INVITE_LING]: 0,
      [ITEM_ID.PARTNER_EXCHANGE_LETTER]: 0
    }
    state.lastUpdatedAt = Date.now()
  }
}

const actions = {
  // 初始化：根据角色信息初始化货币，并随后拉取背包道具（保留原逻辑）
  async initFromRoleInfo({ commit, dispatch }, roleInfo) {
    try {
      if (roleInfo && roleInfo.item) {
        const map = roleInfo.item
        // 仅初始化货币类条目
        commit('SET_CURRENCY', { id: ITEM_ID.COIN, count: map[1] || 0 })
        commit('SET_CURRENCY', { id: ITEM_ID.GOLD_COIN, count: map[2] || 0 })
        commit('SET_CURRENCY', { id: ITEM_ID.INVITE_SCORE, count: map[3] || 0 })
        commit('SET_CURRENCY', { id: ITEM_ID.INVITE_LING, count: map[4] || 0 })
        commit('SET_CURRENCY', { id: ITEM_ID.PARTNER_EXCHANGE_LETTER, count: map[26] || 0 })
      }
      // 可在此处继续拉取背包道具列表（省略）
    } catch (e) { console.warn('initFromRoleInfo error', e) }
  },
  // 新增：从首页home接口返回的item映射中应用货币
  applyCurrenciesFromHomeMap({ commit }, itemMap) {
    try {
      if (!itemMap || typeof itemMap !== 'object') return
      commit('SET_CURRENCY', { id: ITEM_ID.COIN, count: itemMap[1] || 0 })
      commit('SET_CURRENCY', { id: ITEM_ID.GOLD_COIN, count: itemMap[2] || 0 })
      commit('SET_CURRENCY', { id: ITEM_ID.INVITE_SCORE, count: itemMap[3] || 0 })
      commit('SET_CURRENCY', { id: ITEM_ID.INVITE_LING, count: itemMap[4] || 0 })
      commit('SET_CURRENCY', { id: ITEM_ID.PARTNER_EXCHANGE_LETTER, count: itemMap[26] || 0 })
    } catch (e) { console.warn('applyCurrenciesFromHomeMap error', e) }
  },
  // 保留原本的物品数组应用入口，供全局钩子调用
  applyItemsFromArray({ commit }, itemsArray) {
    if (Array.isArray(itemsArray)) {
      commit('APPLY_ITEM_UPDATES', itemsArray)
    }
  }
}

const getters = {
  // 获取某物品数量（自动兼容货币与道具）
  getItemCount: (state) => (id) => {
    if (id in state.currencies) return state.currencies[id] || 0
    return state.inventory[id] || 0
  },
  coin: (state) => state.currencies[ITEM_ID.COIN] || 0,
  goldCoin: (state) => state.currencies[ITEM_ID.GOLD_COIN] || 0,
  inviteScore: (state) => state.currencies[ITEM_ID.INVITE_SCORE] || 0,
  inviteLing: (state) => state.currencies[ITEM_ID.INVITE_LING] || 0,
  partnerExchangeLetter: (state) => state.currencies[ITEM_ID.PARTNER_EXCHANGE_LETTER] || 0,
  inventoryList: (state) => Object.entries(state.inventory).map(([id, count]) => ({ id: Number(id), count })),
  lastUpdatedAt: (state) => state.lastUpdatedAt
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}